package api

import (
	"database/sql"
	"fmt"
	"net/http"
	"3d-space/internal/database"

	"github.com/gin-gonic/gin"
)

func ToggleSpace(c *gin.Context) {
	userID := c.GetInt64("user_id")
	
	var req struct {
		Enabled bool `json:"enabled"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	_, err := database.DB.Exec(
		"UPDATE users SET space_enabled = ? WHERE id = ?",
		req.Enabled, userID,
	)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"space_enabled": req.Enabled})
}

func GetPublicSpace(c *gin.Context) {
	username := c.Param("username")

	// 检查用户是否开启空间
	var spaceEnabled bool
	var userID int64
	err := database.DB.QueryRow(
		"SELECT id, space_enabled FROM users WHERE username = ?",
		username,
	).Scan(&userID, &spaceEnabled)

	if err == sql.ErrNoRows {
		c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
		return
	}

	if !spaceEnabled {
		c.JSON(http.StatusForbidden, gin.H{"error": "该用户未开启空间分享"})
		return
	}

	// 获取用户的所有已完成的模型（不含文件数据）
	rows, err := database.DB.Query(`
		SELECT id, name, description, file_format, status, created_at 
		FROM models WHERE user_id = ? AND status = 'completed' ORDER BY created_at DESC
	`, userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
		return
	}
	defer rows.Close()

	models := []gin.H{}
	for rows.Next() {
		var m database.Model
		rows.Scan(&m.ID, &m.Name, &m.Description, &m.FileFormat, &m.Status, &m.CreatedAt)
		
		// 获取留言数
		var commentCount int
		database.DB.QueryRow("SELECT COUNT(*) FROM comments WHERE model_id = ?", m.ID).Scan(&commentCount)
		
		models = append(models, gin.H{
			"id":            m.ID,
			"name":          m.Name,
			"description":   m.Description,
			"status":        m.Status,
			"file_url":      fmt.Sprintf("/api/model/%d/file", m.ID),
			"comment_count": commentCount,
			"created_at":    m.CreatedAt,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"username": username,
		"models":   models,
	})
}
